#!/bin/bash

# EKS Add-on Compatibility Analysis Script
# This script analyzes EKS add-on compatibility with target EKS versions
# and generates upgrade recommendations based on compatibility matrices

# Color codes for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
PURPLE='\033[0;35m'
CYAN='\033[0;36m'
NC='\033[0m' # No Color

# Print functions
print_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

print_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

print_compatible() {
    echo -e "${GREEN}[✅ COMPATIBLE]${NC} $1"
}

print_upgrade_required() {
    echo -e "${RED}[❌ UPGRADE_REQUIRED]${NC} $1"
}

print_upgrade_recommended() {
    echo -e "${YELLOW}[⚠️ UPGRADE_RECOMMENDED]${NC} $1"
}

# Function to show usage
show_usage() {
    cat << EOF
Usage: $0 -c CLUSTER_NAME -r REGION -t TARGET_EKS_VERSION [OPTIONS]

Required:
  -c, --cluster     EKS cluster name
  -r, --region      AWS region
  -t, --target      Target EKS version (e.g., 1.28, 1.29, 1.30)

Optional:
  -p, --path        Upgrade path (comma-separated versions, e.g., "1.27,1.28,1.29,1.30")
  -f, --format      Output format: text|json|yaml (default: text)
  -o, --output      Output directory (default: ./compatibility-analysis-TIMESTAMP)
  -v, --verbose     Verbose output
  --aws-profile     AWS profile to use
  -h, --help        Show this help message

Examples:
  $0 -c my-cluster -r us-east-1 -t 1.28
  $0 -c my-cluster -r us-east-1 -p "1.27,1.28,1.29,1.30" -f json
  $0 -c my-cluster -r us-east-1 -t 1.30 --aws-profile production

Description:
This script analyzes EKS add-on compatibility with target EKS versions and generates
upgrade recommendations. It helps minimize add-on upgrades by identifying which add-ons
are already compatible and which ones require upgrades.

The script uses manually collected compatibility data from EKS-Addon-Version-Matrix.md
(collected on Sat 9 Aug 2025 15:58:24 CST from us-east-2 region).

EOF
}

# Parse command line arguments
CLUSTER_NAME=""
REGION=""
TARGET_VERSION=""
UPGRADE_PATH=""
FORMAT="text"
OUTPUT_DIR=""
VERBOSE=false
AWS_PROFILE=""

while [[ $# -gt 0 ]]; do
    case $1 in
        -c|--cluster)
            CLUSTER_NAME="$2"
            shift 2
            ;;
        -r|--region)
            REGION="$2"
            shift 2
            ;;
        -t|--target)
            TARGET_VERSION="$2"
            shift 2
            ;;
        -p|--path)
            UPGRADE_PATH="$2"
            shift 2
            ;;
        -f|--format)
            FORMAT="$2"
            shift 2
            ;;
        -o|--output)
            OUTPUT_DIR="$2"
            shift 2
            ;;
        -v|--verbose)
            VERBOSE=true
            shift
            ;;
        --aws-profile)
            AWS_PROFILE="$2"
            shift 2
            ;;
        -h|--help)
            show_usage
            exit 0
            ;;
        *)
            echo "Unknown option $1"
            show_usage
            exit 1
            ;;
    esac
done

# Validate required parameters
if [[ -z "$CLUSTER_NAME" || -z "$REGION" ]]; then
    print_error "Cluster name and region are required"
    show_usage
    exit 1
fi

if [[ -z "$TARGET_VERSION" && -z "$UPGRADE_PATH" ]]; then
    print_error "Either target version (-t) or upgrade path (-p) is required"
    show_usage
    exit 1
fi

# Set default output directory
if [[ -z "$OUTPUT_DIR" ]]; then
    OUTPUT_DIR="./compatibility-analysis-$(date +%Y%m%d-%H%M%S)"
fi

# Create output directory
mkdir -p "$OUTPUT_DIR"

# Set AWS profile if provided
if [[ -n "$AWS_PROFILE" ]]; then
    export AWS_PROFILE="$AWS_PROFILE"
fi

print_info "Using manually collected compatibility matrix from EKS-Addon-Version-Matrix.md"
print_info "Data collection date: Sat 9 Aug 2025 15:58:24 CST (Region: us-east-2)"
print_warning "For production use, consider refreshing compatibility data periodically"
echo ""
print_info "Starting EKS add-on compatibility analysis"
print_info "Cluster: $CLUSTER_NAME"
print_info "Region: $REGION"
if [[ -n "$TARGET_VERSION" ]]; then
    print_info "Target EKS Version: $TARGET_VERSION"
fi
if [[ -n "$UPGRADE_PATH" ]]; then
    print_info "Upgrade Path: $UPGRADE_PATH"
fi
print_info "Output Directory: $OUTPUT_DIR"

# Initialize results
RESULTS_FILE="$OUTPUT_DIR/compatibility-analysis.json"
echo '{"timestamp":"'$(date -Iseconds)'","cluster":"'$CLUSTER_NAME'","region":"'$REGION'","analysis":{}}' > "$RESULTS_FILE"

# Function to get real-time compatibility data from AWS CLI
get_real_compatibility_range() {
    local addon="$1"
    local eks_version="$2"
    
    if [[ "$VERBOSE" == "true" ]]; then
        print_info "Fetching real-time compatibility data for $addon on EKS $eks_version..."
    fi
    
    # Try to get compatible versions from AWS CLI
    local versions=$(aws eks describe-addon-versions \
        --kubernetes-version "$eks_version" \
        --addon-name "$addon" \
        --query 'addons[0].addonVersions[*].addonVersion' \
        --output text 2>/dev/null | tr '\t' ' ')
    
    if [[ -n "$versions" && "$versions" != "None" ]]; then
        # Get min and max versions
        local min_version=$(echo "$versions" | tr ' ' '\n' | sort -V | head -n1)
        local max_version=$(echo "$versions" | tr ' ' '\n' | sort -V | tail -n1)
        echo "$min_version $max_version"
        return 0
    else
        # Fall back to built-in matrix
        if [[ "$VERBOSE" == "true" ]]; then
            print_warning "AWS CLI query failed, falling back to built-in matrix for $addon"
        fi
        get_compatibility_range "$addon" "$eks_version"
        return 1
    fi
}

# Add analysis result function
add_analysis_result() {
    local eks_version="$1"
    local addon_name="$2"
    local current_version="$3"
    local compatibility_status="$4"
    local action="$5"
    local target_version="$6"
    local reason="$7"
    local risk_level="$8"
    
    jq --arg eks "$eks_version" --arg addon "$addon_name" --arg current "$current_version" \
       --arg status "$compatibility_status" --arg action "$action" --arg target "$target_version" \
       --arg reason "$reason" --arg risk "$risk_level" \
       '.analysis[$eks] += [{
         addon: $addon,
         current_version: $current,
         compatibility_status: $status,
         action: $action,
         target_version: $target,
         reason: $reason,
         risk_level: $risk
       }]' "$RESULTS_FILE" > "$RESULTS_FILE.tmp" && mv "$RESULTS_FILE.tmp" "$RESULTS_FILE"
}

# Compatibility matrix - Based on manually collected real data
# 
# Data source: EKS-Addon-Version-Matrix.md
# Collection date: Sat 9 Aug 2025 15:58:24 CST
# Region: us-east-2
# Method: AWS CLI describe-addon-versions queries
# 
# This matrix contains REAL compatibility data collected from AWS APIs.
# For the most current data, you can still use AWS CLI:
# 
# aws eks describe-addon-versions --addon-name ADDON_NAME
# aws eks describe-addon-versions --kubernetes-version EKS_VERSION --addon-name ADDON_NAME
# 
# The built-in matrix below uses actual AWS data and should be accurate
# for the collection date above. For production use, consider refreshing
# this data periodically.
get_compatibility_range() {
    local addon="$1"
    local eks_version="$2"
    
    # Based on manually collected data from EKS-Addon-Version-Matrix.md
    # Data collection date: Sat 9 Aug 2025 15:58:24 CST
    # Region: us-east-2
    
    case "$addon" in
        "vpc-cni")
            case "$eks_version" in
                "1.27") echo "v1.12.5-eksbuild.2 v1.20.0-eksbuild.1" ;;
                "1.28") echo "v1.13.3-eksbuild.1 v1.20.0-eksbuild.1" ;;
                "1.29") echo "v1.13.4-eksbuild.1 v1.20.0-eksbuild.1" ;;
                "1.30") echo "v1.16.0-eksbuild.1 v1.20.0-eksbuild.1" ;;
                "1.31") echo "v1.16.0-eksbuild.1 v1.20.0-eksbuild.1" ;;
                "1.32") echo "v1.17.1-eksbuild.1 v1.20.0-eksbuild.1" ;;
                "1.33") echo "v1.17.1-eksbuild.1 v1.20.0-eksbuild.1" ;;
                *) echo "unknown unknown" ;;
            esac
            ;;
        "coredns")
            case "$eks_version" in
                "1.27") echo "v1.9.3-eksbuild.2 v1.10.1-eksbuild.35" ;;
                "1.28") echo "v1.9.3-eksbuild.2 v1.10.1-eksbuild.35" ;;
                "1.29") echo "v1.10.1-eksbuild.1 v1.11.4-eksbuild.14" ;;
                "1.30") echo "v1.10.1-eksbuild.1 v1.11.4-eksbuild.14" ;;
                "1.31") echo "v1.10.1-eksbuild.1 v1.11.4-eksbuild.14" ;;
                "1.32") echo "v1.11.1-eksbuild.3 v1.11.4-eksbuild.14" ;;
                "1.33") echo "v1.11.1-eksbuild.3 v1.12.2-eksbuild.4" ;;
                *) echo "unknown unknown" ;;
            esac
            ;;
        "kube-proxy")
            case "$eks_version" in
                "1.27") echo "v1.25.6-eksbuild.1 v1.27.16-eksbuild.35" ;;
                "1.28") echo "v1.25.6-eksbuild.1 v1.28.15-eksbuild.25" ;;
                "1.29") echo "v1.26.2-eksbuild.1 v1.29.15-eksbuild.10" ;;
                "1.30") echo "v1.27.1-eksbuild.1 v1.30.14-eksbuild.2" ;;
                "1.31") echo "v1.28.1-eksbuild.1 v1.31.10-eksbuild.2" ;;
                "1.32") echo "v1.29.0-eksbuild.1 v1.32.6-eksbuild.2" ;;
                "1.33") echo "v1.30.0-eksbuild.2 v1.33.0-eksbuild.2" ;;
                *) echo "unknown unknown" ;;
            esac
            ;;
        "aws-ebs-csi-driver")
            case "$eks_version" in
                "1.27") echo "v1.11.5-eksbuild.1 v1.46.0-eksbuild.1" ;;
                "1.28") echo "v1.17.0-eksbuild.1 v1.47.0-eksbuild.1" ;;
                "1.29") echo "v1.20.0-eksbuild.1 v1.47.0-eksbuild.1" ;;
                "1.30") echo "v1.26.1-eksbuild.1 v1.47.0-eksbuild.1" ;;
                "1.31") echo "v1.29.1-eksbuild.1 v1.47.0-eksbuild.1" ;;
                "1.32") echo "v1.29.1-eksbuild.1 v1.47.0-eksbuild.1" ;;
                "1.33") echo "v1.29.1-eksbuild.1 v1.47.0-eksbuild.1" ;;
                *) echo "unknown unknown" ;;
            esac
            ;;
        "aws-efs-csi-driver")
            case "$eks_version" in
                "1.27") echo "v1.5.8-eksbuild.1 v2.1.10-eksbuild.1" ;;
                "1.28") echo "v1.5.8-eksbuild.1 v2.1.10-eksbuild.1" ;;
                "1.29") echo "v1.5.8-eksbuild.1 v2.1.10-eksbuild.1" ;;
                "1.30") echo "v1.5.8-eksbuild.1 v2.1.10-eksbuild.1" ;;
                "1.31") echo "v1.5.8-eksbuild.1 v2.1.10-eksbuild.1" ;;
                "1.32") echo "v1.5.8-eksbuild.1 v2.1.10-eksbuild.1" ;;
                "1.33") echo "v1.5.8-eksbuild.1 v2.1.10-eksbuild.1" ;;
                *) echo "unknown unknown" ;;
            esac
            ;;
        "aws-mountpoint-s3-csi-driver")
            case "$eks_version" in
                "1.27") echo "v1.0.0-eksbuild.1 v1.15.0-eksbuild.1" ;;
                "1.28") echo "v1.0.0-eksbuild.1 v1.15.0-eksbuild.1" ;;
                "1.29") echo "v1.0.0-eksbuild.1 v1.15.0-eksbuild.1" ;;
                "1.30") echo "v1.3.1-eksbuild.1 v1.15.0-eksbuild.1" ;;
                "1.31") echo "v1.6.0-eksbuild.1 v1.15.0-eksbuild.1" ;;
                "1.32") echo "v1.8.1-eksbuild.1 v1.15.0-eksbuild.1" ;;
                "1.33") echo "v1.10.0-eksbuild.1 v1.15.0-eksbuild.1" ;;
                *) echo "unknown unknown" ;;
            esac
            ;;
        "aws-fsx-csi-driver")
            case "$eks_version" in
                "1.27") echo "v1.3.0-eksbuild.1 v1.10.1-eksbuild.1" ;;
                "1.28") echo "v1.3.0-eksbuild.1 v1.10.1-eksbuild.1" ;;
                "1.29") echo "v1.3.0-eksbuild.1 v1.10.1-eksbuild.1" ;;
                "1.30") echo "v1.3.0-eksbuild.1 v1.10.1-eksbuild.1" ;;
                "1.31") echo "v1.3.0-eksbuild.1 v1.10.1-eksbuild.1" ;;
                "1.32") echo "v1.3.0-eksbuild.1 v1.10.1-eksbuild.1" ;;
                "1.33") echo "v1.3.0-eksbuild.1 v1.10.1-eksbuild.1" ;;
                *) echo "unknown unknown" ;;
            esac
            ;;
        "external-dns")
            case "$eks_version" in
                "1.27") echo "v0.15.1-eksbuild.1 v0.15.1-eksbuild.1" ;;
                "1.28") echo "v0.15.1-eksbuild.1 v0.15.1-eksbuild.1" ;;
                "1.29") echo "v0.15.1-eksbuild.1 v0.15.1-eksbuild.1" ;;
                "1.30") echo "v0.15.1-eksbuild.1 v0.15.1-eksbuild.1" ;;
                "1.31") echo "v0.15.1-eksbuild.1 v0.15.1-eksbuild.1" ;;
                "1.32") echo "v0.15.1-eksbuild.1 v0.15.1-eksbuild.1" ;;
                "1.33") echo "v0.15.1-eksbuild.1 v0.15.1-eksbuild.1" ;;
                *) echo "unknown unknown" ;;
            esac
            ;;
        *)
            echo "unknown unknown"
            ;;
    esac
}

# Version comparison function
version_compare() {
    local version1="$1"
    local version2="$2"
    
    # Remove 'v' prefix and '-eksbuild.x' suffix for comparison
    local v1=$(echo "$version1" | sed 's/^v//; s/-eksbuild.*$//')
    local v2=$(echo "$version2" | sed 's/^v//; s/-eksbuild.*$//')
    
    # Use sort -V for version comparison
    if [[ "$v1" == "$v2" ]]; then
        echo "0"  # equal
    elif [[ "$(printf '%s\n%s' "$v1" "$v2" | sort -V | head -n1)" == "$v1" ]]; then
        echo "-1" # v1 < v2
    else
        echo "1"  # v1 > v2
    fi
}

# Check compatibility function
check_compatibility() {
    local addon="$1"
    local current_version="$2"
    local eks_version="$3"
    
    local range=$(get_compatibility_range "$addon" "$eks_version")
    local min_version=$(echo "$range" | awk '{print $1}')
    local max_version=$(echo "$range" | awk '{print $2}')
    
    if [[ "$min_version" == "unknown" ]]; then
        echo "NEEDS_ANALYSIS"
        return
    fi
    
    local min_compare=$(version_compare "$current_version" "$min_version")
    local max_compare=$(version_compare "$current_version" "$max_version")
    
    if [[ $min_compare -ge 0 && $max_compare -le 0 ]]; then
        echo "COMPATIBLE"
    else
        echo "UPGRADE_REQUIRED"
    fi
}

# Get recommended version function
get_recommended_version() {
    local addon="$1"
    local eks_version="$2"
    
    # Return the default version from the manually collected matrix
    # Based on EKS-Addon-Version-Matrix.md data
    case "$addon" in
        "vpc-cni")
            case "$eks_version" in
                "1.27") echo "v1.19.0-eksbuild.1" ;;
                "1.28") echo "v1.19.0-eksbuild.1" ;;
                "1.29") echo "v1.19.0-eksbuild.1" ;;
                "1.30") echo "v1.19.0-eksbuild.1" ;;
                "1.31") echo "v1.19.0-eksbuild.1" ;;
                "1.32") echo "v1.19.2-eksbuild.1" ;;
                "1.33") echo "v1.19.5-eksbuild.1" ;;
                *) echo "latest" ;;
            esac
            ;;
        "coredns")
            case "$eks_version" in
                "1.27") echo "v1.10.1-eksbuild.4" ;;
                "1.28") echo "v1.10.1-eksbuild.4" ;;
                "1.29") echo "v1.11.1-eksbuild.4" ;;
                "1.30") echo "v1.11.1-eksbuild.8" ;;
                "1.31") echo "v1.11.3-eksbuild.1" ;;
                "1.32") echo "v1.11.4-eksbuild.2" ;;
                "1.33") echo "v1.12.1-eksbuild.2" ;;
                *) echo "latest" ;;
            esac
            ;;
        "kube-proxy")
            case "$eks_version" in
                "1.27") echo "v1.27.6-eksbuild.2" ;;
                "1.28") echo "v1.28.15-eksbuild.4" ;;
                "1.29") echo "v1.29.10-eksbuild.3" ;;
                "1.30") echo "v1.30.6-eksbuild.3" ;;
                "1.31") echo "v1.31.2-eksbuild.3" ;;
                "1.32") echo "v1.32.0-eksbuild.2" ;;
                "1.33") echo "v1.33.0-eksbuild.2" ;;
                *) echo "latest" ;;
            esac
            ;;
        "aws-ebs-csi-driver")
            case "$eks_version" in
                "1.27") echo "v1.46.0-eksbuild.1" ;;
                "1.28") echo "v1.47.0-eksbuild.1" ;;
                "1.29") echo "v1.47.0-eksbuild.1" ;;
                "1.30") echo "v1.47.0-eksbuild.1" ;;
                "1.31") echo "v1.47.0-eksbuild.1" ;;
                "1.32") echo "v1.47.0-eksbuild.1" ;;
                "1.33") echo "v1.47.0-eksbuild.1" ;;
                *) echo "latest" ;;
            esac
            ;;
        "aws-efs-csi-driver")
            case "$eks_version" in
                "1.27") echo "v2.1.10-eksbuild.1" ;;
                "1.28") echo "v2.1.10-eksbuild.1" ;;
                "1.29") echo "v2.1.10-eksbuild.1" ;;
                "1.30") echo "v2.1.10-eksbuild.1" ;;
                "1.31") echo "v2.1.10-eksbuild.1" ;;
                "1.32") echo "v2.1.10-eksbuild.1" ;;
                "1.33") echo "v2.1.10-eksbuild.1" ;;
                *) echo "latest" ;;
            esac
            ;;
        "aws-mountpoint-s3-csi-driver")
            case "$eks_version" in
                "1.27") echo "v1.15.0-eksbuild.1" ;;
                "1.28") echo "v1.15.0-eksbuild.1" ;;
                "1.29") echo "v1.15.0-eksbuild.1" ;;
                "1.30") echo "v1.15.0-eksbuild.1" ;;
                "1.31") echo "v1.15.0-eksbuild.1" ;;
                "1.32") echo "v1.15.0-eksbuild.1" ;;
                "1.33") echo "v1.15.0-eksbuild.1" ;;
                *) echo "latest" ;;
            esac
            ;;
        "aws-fsx-csi-driver")
            case "$eks_version" in
                "1.27") echo "v1.10.1-eksbuild.1" ;;
                "1.28") echo "v1.10.1-eksbuild.1" ;;
                "1.29") echo "v1.10.1-eksbuild.1" ;;
                "1.30") echo "v1.10.1-eksbuild.1" ;;
                "1.31") echo "v1.10.1-eksbuild.1" ;;
                "1.32") echo "v1.10.1-eksbuild.1" ;;
                "1.33") echo "v1.10.1-eksbuild.1" ;;
                *) echo "latest" ;;
            esac
            ;;
        "external-dns")
            case "$eks_version" in
                "1.27") echo "v0.15.1-eksbuild.1" ;;
                "1.28") echo "v0.15.1-eksbuild.1" ;;
                "1.29") echo "v0.15.1-eksbuild.1" ;;
                "1.30") echo "v0.15.1-eksbuild.1" ;;
                "1.31") echo "v0.15.1-eksbuild.1" ;;
                "1.32") echo "v0.15.1-eksbuild.1" ;;
                "1.33") echo "v0.15.1-eksbuild.1" ;;
                *) echo "latest" ;;
            esac
            ;;
        *)
            echo "latest"
            ;;
    esac
}

# Get risk level function
get_risk_level() {
    local addon="$1"
    local current_version="$2"
    local target_version="$3"
    
    # Extract version numbers for comparison
    local current_major=$(echo "$current_version" | sed 's/^v//; s/-eksbuild.*$//' | cut -d. -f1)
    local current_minor=$(echo "$current_version" | sed 's/^v//; s/-eksbuild.*$//' | cut -d. -f2)
    local target_major=$(echo "$target_version" | sed 's/^v//; s/-eksbuild.*$//' | cut -d. -f1)
    local target_minor=$(echo "$target_version" | sed 's/^v//; s/-eksbuild.*$//' | cut -d. -f2)
    
    # Calculate version difference
    local major_diff=$((target_major - current_major))
    local minor_diff=$((target_minor - current_minor))
    
    if [[ $major_diff -gt 0 ]]; then
        echo "HIGH"
    elif [[ $minor_diff -gt 2 ]]; then
        echo "MEDIUM"
    elif [[ $minor_diff -gt 0 ]]; then
        echo "LOW"
    else
        echo "LOW"
    fi
}

# Get current add-on versions
get_current_addon_versions() {
    local cluster="$1"
    local region="$2"
    
    print_info "Retrieving current add-on versions..."
    
    # Get list of installed add-ons (disable color output)
    local addons_raw=$(AWS_PAGER="" aws eks list-addons --cluster-name "$cluster" --region "$region" --query 'addons[]' --output text --no-cli-pager 2>/dev/null)
    
    if [[ -z "$addons_raw" ]]; then
        print_warning "No managed add-ons found in cluster $cluster"
        return 1
    fi
    
    # Convert tab-separated output to array
    IFS=$'\t' read -ra addons_array <<< "$addons_raw"
    
    # Process each addon
    for addon in "${addons_array[@]}"; do
        # Clean addon name (remove any whitespace and ANSI color codes)
        addon=$(echo "$addon" | sed 's/\x1b\[[0-9;]*m//g' | xargs)
        
        if [[ -n "$addon" && "$addon" != "None" ]]; then
            local version=$(AWS_PAGER="" aws eks describe-addon --cluster-name "$cluster" --addon-name "$addon" --region "$region" --query 'addon.addonVersion' --output text --no-cli-pager 2>/dev/null)
            if [[ $? -eq 0 && "$version" != "None" && -n "$version" ]]; then
                # Clean version string
                version=$(echo "$version" | sed 's/\x1b\[[0-9;]*m//g' | xargs)
                echo "$addon:$version"
                if [[ "$VERBOSE" == "true" ]]; then
                    print_info "Found $addon: $version" >&2
                fi
            fi
        fi
    done
}

# Analyze compatibility for a specific EKS version
analyze_compatibility() {
    local target_eks_version="$1"
    local cluster="$2"
    local region="$3"
    
    print_info "Analyzing compatibility for EKS $target_eks_version"
    echo "=================================================="
    
    # Get current add-on versions
    local addon_data=$(get_current_addon_versions "$cluster" "$region")
    
    if [[ -z "$addon_data" ]]; then
        print_error "Failed to retrieve add-on versions"
        return 1
    fi
    
    local upgrade_required=()
    local keep_current=()
    
    while IFS=':' read -r addon current_version; do
        # Clean addon name and version (remove ANSI color codes)
        addon=$(echo "$addon" | sed 's/\x1b\[[0-9;]*m//g' | xargs)
        current_version=$(echo "$current_version" | sed 's/\x1b\[[0-9;]*m//g' | xargs)
        
        if [[ -z "$addon" || -z "$current_version" ]]; then
            continue
        fi
        
        # Skip invalid addon names (like "0" or numbers)
        if [[ "$addon" =~ ^[0-9]+$ ]]; then
            if [[ "$VERBOSE" == "true" ]]; then
                print_warning "Skipping invalid addon name: '$addon'"
            fi
            continue
        fi
        
        local compatibility=$(check_compatibility "$addon" "$current_version" "$target_eks_version")
        local range=$(get_compatibility_range "$addon" "$target_eks_version")
        local min_version=$(echo "$range" | awk '{print $1}')
        local max_version=$(echo "$range" | awk '{print $2}')
        
        case "$compatibility" in
            "COMPATIBLE")
                print_compatible "$addon $current_version is compatible with EKS $target_eks_version ($min_version~$max_version)"
                keep_current+=("$addon:$current_version")
                add_analysis_result "$target_eks_version" "$addon" "$current_version" "COMPATIBLE" "KEEP" "-" "Current version is within compatibility range ($min_version~$max_version)" "LOW"
                ;;
            "UPGRADE_REQUIRED")
                local recommended_version=$(get_recommended_version "$addon" "$target_eks_version")
                local risk_level=$(get_risk_level "$addon" "$current_version" "$recommended_version")
                print_upgrade_required "$addon $current_version is NOT compatible with EKS $target_eks_version (requires $min_version~$max_version)"
                print_info "  → Recommended upgrade to: $recommended_version (Risk: $risk_level)"
                upgrade_required+=("$addon:$current_version:$recommended_version:$risk_level")
                add_analysis_result "$target_eks_version" "$addon" "$current_version" "UPGRADE_REQUIRED" "UPGRADE" "$recommended_version" "Current version is outside compatibility range, requires $min_version~$max_version" "$risk_level"
                ;;
            "NEEDS_ANALYSIS")
                print_warning "$addon $current_version compatibility with EKS $target_eks_version needs manual analysis"
                add_analysis_result "$target_eks_version" "$addon" "$current_version" "NEEDS_ANALYSIS" "MANUAL_CHECK" "-" "Compatibility matrix not available, manual analysis required" "UNKNOWN"
                ;;
        esac
    done <<< "$addon_data"
    
    # Generate summary
    echo ""
    print_info "=== UPGRADE DECISION SUMMARY FOR EKS $target_eks_version ==="
    
    if [[ ${#keep_current[@]} -gt 0 ]]; then
        echo ""
        print_success "Add-ons to KEEP (${#keep_current[@]}):"
        for item in "${keep_current[@]}"; do
            IFS=':' read -r addon version <<< "$item"
            echo "  ✅ $addon: $version"
        done
    fi
    
    if [[ ${#upgrade_required[@]} -gt 0 ]]; then
        echo ""
        print_warning "Add-ons to UPGRADE (${#upgrade_required[@]}):"
        for item in "${upgrade_required[@]}"; do
            IFS=':' read -r addon current target risk <<< "$item"
            echo "  ❌ $addon: $current → $target (Risk: $risk)"
        done
    fi
    
    echo ""
    print_info "Risk Assessment:"
    echo "  - LOW: Minor version upgrade, minimal configuration impact"
    echo "  - MEDIUM: Moderate version jump, may affect some configurations"
    echo "  - HIGH: Major version upgrade, significant configuration review needed"
    
    # Generate upgrade commands
    if [[ ${#upgrade_required[@]} -gt 0 ]]; then
        echo ""
        print_info "=== UPGRADE COMMANDS ==="
        local upgrade_script="$OUTPUT_DIR/upgrade-addons-eks-$target_eks_version.sh"
        cat > "$upgrade_script" << 'EOF'
#!/bin/bash
# Auto-generated add-on upgrade script
# Generated by analyze-addon-compatibility.sh

set -e

CLUSTER_NAME="$1"
REGION="$2"

if [[ -z "$CLUSTER_NAME" || -z "$REGION" ]]; then
    echo "Usage: $0 CLUSTER_NAME REGION"
    exit 1
fi

echo "Starting add-on upgrades for cluster: $CLUSTER_NAME in region: $REGION"

EOF
        
        for item in "${upgrade_required[@]}"; do
            IFS=':' read -r addon current target risk <<< "$item"
            cat >> "$upgrade_script" << EOF

echo "Upgrading $addon from $current to $target (Risk: $risk)..."
aws eks update-addon \\
    --cluster-name "\$CLUSTER_NAME" \\
    --addon-name "$addon" \\
    --addon-version "$target" \\
    --region "\$REGION" \\
    --resolve-conflicts OVERWRITE

echo "Waiting for $addon upgrade to complete..."
aws eks wait addon-active \\
    --cluster-name "\$CLUSTER_NAME" \\
    --addon-name "$addon" \\
    --region "\$REGION"

echo "$addon upgrade completed successfully"
EOF
        done
        
        cat >> "$upgrade_script" << 'EOF'

echo "All add-on upgrades completed successfully!"
EOF
        
        chmod +x "$upgrade_script"
        print_success "Upgrade script generated: $upgrade_script"
        echo "  Usage: $upgrade_script CLUSTER_NAME REGION"
    fi
}

# Main execution
main() {
    # Check if jq is installed
    if ! command -v jq &> /dev/null; then
        print_error "jq is required but not installed. Please install jq first."
        exit 1
    fi
    
    # Check AWS CLI
    if ! command -v aws &> /dev/null; then
        print_error "AWS CLI is required but not installed. Please install AWS CLI first."
        exit 1
    fi
    
    # Test AWS credentials
    if ! aws sts get-caller-identity &> /dev/null; then
        print_error "AWS credentials not configured or invalid. Please configure AWS CLI first."
        exit 1
    fi
    
    # Analyze single target version
    if [[ -n "$TARGET_VERSION" ]]; then
        analyze_compatibility "$TARGET_VERSION" "$CLUSTER_NAME" "$REGION"
    fi
    
    # Analyze upgrade path
    if [[ -n "$UPGRADE_PATH" ]]; then
        IFS=',' read -ra VERSIONS <<< "$UPGRADE_PATH"
        for version in "${VERSIONS[@]}"; do
            version=$(echo "$version" | xargs) # trim whitespace
            if [[ "$version" =~ ^[0-9]+\.[0-9]+$ ]]; then
                echo ""
                echo "######################################################"
                analyze_compatibility "$version" "$CLUSTER_NAME" "$REGION"
                echo "######################################################"
            else
                print_warning "Skipping invalid version format: $version"
            fi
        done
    fi
    
    # Generate final report
    print_info "Analysis complete. Results saved to: $OUTPUT_DIR"
    
    if [[ "$FORMAT" == "json" ]]; then
        print_info "JSON report: $RESULTS_FILE"
    elif [[ "$FORMAT" == "yaml" ]]; then
        local yaml_file="$OUTPUT_DIR/compatibility-analysis.yaml"
        if command -v yq &> /dev/null; then
            yq eval "$RESULTS_FILE" > "$yaml_file"
            print_info "YAML report: $yaml_file"
        else
            print_warning "yq not found, YAML output not generated"
        fi
    fi
    
    print_success "EKS add-on compatibility analysis completed successfully!"
}

# Run main function
main "$@"